<template>
  <div style="height: 100%;border-radius: 10px;">
    <div style="height: 10%;padding: 15px;display: flex;justify-content: space-between">
      <div>
        <el-input v-model="data.inpVal1" style="width: 200px;" placeholder="请输入角色名称"></el-input>
        <el-button type="primary" @click="load" style="margin-left: 10px">搜索</el-button>
        <el-button plain type="warning" @click="reset" style="margin-left: 10px">重置</el-button>
      </div>
      <div style="display: flex">
        <el-button type="success" @click="addInfo">新增</el-button>
      </div>
    </div>
    <div>
      <div style="color: red;font-size: 14px">
        选子菜单时切记要选上父菜单(例:<span style="color: #0085ff"> 用户管理 </span>是<span style="color: #0085ff"> 系统功能 </span>的子菜单),
        只选其一不生效！（不选择权限即赋予所有权限）
      </div>
      <el-table
          v-loading="data.loading"
          height="440"
          :data="data.tableData"
          :default-sort="{ prop: 'id', order: 'descending' }"
          border
          style="width: 100%;"
      >
        <el-table-column prop="permRoleId" label="编号" width="55" sortable align="center" />
        <el-table-column prop="roleName" label="角色名称" width="120" align="center" />
        <el-table-column prop="remark" show-overflow-tooltip label="备注" align="center" />
        <el-table-column prop="perm" label="权限选择" width="450" align="center">
          <template v-slot="scope">
            <el-select
                v-model="scope.row.perm"
                multiple
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="4"
                placeholder="请选中权限"
            >
              <el-option
                  v-for="item in data.roleOptions"
                  :key="item.id"
                  :label="item.name +
                  (item.isOne === 0 && item.pno != null? ('-->'+item.pno+'子菜单'): '') +
                  ((item.isOne === 0 && item.pno == null)?('-->'+item.path):'')"
                  :value="item.id"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template v-slot="scope">
            <el-button type="primary" :icon="Edit" size="small" @click="updateInfo(scope.row)"/>
            <el-button type="success" size="small" @click="permAllot(scope.row)">分配权限</el-button>
            <el-button type="danger" :icon="Delete" size="small" @click="del(scope.row.id)"  />
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!--弹窗-->
    <el-dialog
        title="数据更新"
        v-model="data.dialog"
        width="35%"
        style="padding: 30px"
        :close-on-click-modal="false">
      <el-form ref="roleFormRef" :rules="data.rules" :model="data.roleForm" label-width="125px">
        <el-form-item prop="roleName" label="角色名称：">
          <el-input v-model="data.roleForm.roleName" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item prop="permRoleId" label="分配角色编号：">
          <el-input v-model="data.roleForm.permRoleId" placeholder="请输入分配角色编号(0/1除外)"></el-input>
        </el-form-item>
        <el-form-item prop="remark" label="备注：">
          <el-input type="textarea" v-model="data.roleForm.remark" placeholder="请输入备注信息"></el-input>
        </el-form-item>
        <div style="display: flex;justify-content: end">
          <el-button type="success" @click="addAndUpdate">提交</el-button>
          <el-button plain type="primary" @click="data.dialog = false">取消</el-button>
        </div>
      </el-form>
    </el-dialog>

    <!-- 分页器 -->
    <div style="width: 200px;margin: 10px -100px;position: relative;left: 50%;">
      <!--
          1.@size-change  赋值每页数据数量
          2.@current-change  赋值页码
          3.pageNum 当前页码
          4.pageSize 每页数量
      -->
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="data.pageNum"
          :page-sizes="[8, 10, 1000]"
          :page-size="data.pageSize"
          background
          layout="prev, pager, next, sizes, total"
          :total="data.total">
      </el-pagination>
    </div>
  </div>
</template>

<script lang="js" setup>
import {ref, reactive, getCurrentInstance} from "vue";
import {ElMessage, ElMessageBox} from "element-plus";
import {Delete, Edit, Star, UserFilled} from "@element-plus/icons-vue";

const {proxy} = getCurrentInstance();
const data = reactive({
  user: JSON.parse(sessionStorage.getItem('user-data')),
  loading: true,
  inpVal1: '',
  pageNum: 1, // 当前页码
  pageSize: 8, // 每页数量
  total: 0,
  tableData: [],
  dialog: false, // 弹窗
  roleForm: {}, // 弹窗表单
  roleVal: null, // 已选权限
  roleOptions:[],// 权限选择
  rules: {
    roleName: [
      { required: true, message: '请输入角色名称', trigger: 'blur' },
    ],
    permRoleId: [
      { required: true, message: '请输入角色编号', trigger: 'blur' },
    ],
  }
});

/**
 * 获取权限数据
 */
const loadPermRole = () => {
  proxy.$request.get('/role/findPerm').then(res => {
    if (res.code === '200') {
      data.roleOptions = res.data;
    } else {
      ElMessage({type:'error',message:res.msg});
    }
  });
}
loadPermRole();


/**
 * 重置
 */
const reset = () =>{
  data.inpVal1 = '';
  load();
};

/**
 * 分配权限
 */
const permAllot = (row) => {
  ElMessageBox.confirm(
      '确定分配该权限？',
      '分配权限',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    if (row.perm.length <= 0) {
      ElMessage({type: 'warning', message: '分配权限不能为空！'});
      return
    }
    let permIds = '';
    row.perm.forEach(v => {
      permIds += v + ',';
      console.log(permIds)
    });2
    proxy.$request.get('/role/allot/' + row.permRoleId, {
      params:{
        permIds: permIds,
      }
    }).then(res => {
      if (res.code === '200') {
        ElMessage({type: 'success', message: '分配成功！'});
        load();
      } else {
        ElMessage({type: 'error', message: res.msg});
      }
    });
  }).catch(() => {})
}

/**
 * 新增修改
 */
const addInfo = () => {
  data.roleForm = {};
  data.dialog = true;
};
const updateInfo = (row) => {
  data.roleForm = JSON.parse(JSON.stringify(row));
  data.dialog = true;
};
const addAndUpdate = () => {
  proxy.$refs['roleFormRef'].validate(valid => {
    if (valid) {
      proxy.$request({
        url: data.roleForm.id ? '/role/update' : '/role/add',
        method: data.roleForm.id ? 'PUT' : 'POST',
        data: data.roleForm
      }).then(res => {
        if (res.code === '200') {
          data.dialog = false;
          ElMessage({message: '数据更新成功！', type: 'success'});
          load();
        } else {
          ElMessage({message:res.msg,type:'error'});
        }
      });
    }
  });
};

/**
 * 删除
 */
const del = (id) => {
  proxy.$confirm('确定删除该条数据？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'danger'
  }).then(() => {
    proxy.$request.delete('/role/del/' + id).then(res => {
      if (res.code === '200') {
        ElMessage({message: '删除成功！', type: 'success'});
        load();
      } else {
        ElMessage({message: res.msg, type: 'error'});
      }
    });
  }).catch(() => {});
};

/**
 * 页面加载
 */
const load = ()=>{
  proxy.$request.get('/role/findByPage',{
    params:{
      pageNum: data.pageNum,
      pageSize: data.pageSize,
      roleName: data.inpVal1,
    }
  }).then(res => {
    if (res.data != null) {
      data.tableData = res.data.tlist
      data.total = res.data.total;
    } else {
      ElMessage({message:res.msg,type:'error'});
    }
    data.loading = false;
  });
}
// 调用函数
load();
/**
 * 赋值分页器
 */
const handleSizeChange = (pageSize) => {
  data.pageSize = pageSize;
  load();
};
const handleCurrentChange = (pageNum) => {
  data.pageNum = pageNum;
  load();
};
</script>
<style scoped>

</style>